<template>
  <div class="view">
    <Panel :title="this.$i18n.t('m.Course_Resource_List')">
      <div slot="header">
        <el-input
          v-model="keyword"
          prefix-icon="el-icon-search"
          placeholder="Keywords">
        </el-input>
      </div>
      <el-table
        v-loading="loading"
        element-loading-text="loading"
        ref="table"
        :data="resourceList"
        style="width: 100%">
        <el-table-column
          width="100"
          prop="id"
          label="序号">
        </el-table-column>
        <el-table-column
          prop="title"
          label="标题">
        </el-table-column>
        <el-table-column
          prop="created_by.username"
          label="作者">
        </el-table-column>
        <el-table-column
          width="200"
          prop="create_time"
          label="上传时间">
          <template slot-scope="scope">
            {{scope.row.create_time | localtime }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="250">
          <div slot-scope="scope">
            <icon-btn icon="download" name="下载"
                      @click.native="downloadResource(scope.row.id)"></icon-btn>
            <icon-btn icon="trash" name="删除"
                      @click.native="deleteResource(scope.row.id)"></icon-btn>
          </div>
        </el-table-column>
      </el-table>
      <div class="panel-options">
        <el-upload
          class="upload-demo"
          action="/api/admin/course/resource"
          :show-file-list="false"
          :data="{courseId: courseId}"
          :before-upload="beforeUpload"
          :on-success="uploadSucceeded"
          :on-progress="videoUploadProcess">
          <el-button size="small" type="primary">上传资源</el-button>
          <span slot="tip" class="el-upload__tip">只能上传mp4文件，且不超过150M</span>
        </el-upload>
        <el-progress v-if="showProgress"
          :percentage="videoUploadPercent"
          :format="format"
        ></el-progress>
        <el-pagination
          class="page"
          layout="prev, pager, next"
          @current-change="currentChange"
          :page-size="pageSize"
          :total="total">
        </el-pagination>
      </div>
    </Panel>
  </div>
</template>

<script>
import api from '../../api'
export default {
  name: 'CourseResourceList',
  data () {
    return {
      pageSize: 10,
      total: 0,
      resourceList: [],
      keyword: '',
      loading: false,
      currentPage: 1,
      routeName: '',
      courseId: '',
      // for make public use
      currentResourceID: '',
      currentRow: {},
      videoUploadPercent: 0,
      showProgress: false,
      resource: {
        duration: null
      }
    }
  },
  mounted () {
    this.routeName = this.$route.name
    this.courseId = this.$route.params.courseId
    this.getResourceList(this.currentPage)
  },
  methods: {
    // 切换页码回调
    currentChange (page) {
      this.currentPage = page
      this.getResourceList(page)
    },
    getResourceList (page) {
      this.loading = true
      let offset = (page - 1) * this.pageSize
      api.getResourceList(offset, this.pageSize, this.keyword, this.courseId).then(res => {
        this.loading = false
        this.total = res.data.data.total
        this.resourceList = res.data.data.results
      }, res => {
        this.loading = false
      })
    },
    deleteResource (id) {
      this.$confirm('确定删除此资源吗？', '注意', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // then 为确定
        this.loading = true
        api.deleteCourseResource(id).then(res => {
          this.getResourceList(1)
          this.loading = false
        })
      }).catch(() => {
        // catch 为取消
        this.loading = false
      })
    },
    downloadResource (resourceId) {
      console.log('download resource')
    },
    setDuration (audioElement) {
      this.resource.duration = audioElement.duration
    },
    beforeUpload (file) {
      this.resource.title = file.name
      // 获取视频时长，以秒为单位
      let url = window.URL.createObjectURL(file)
      let audioElement = document.createElement('audio')
      audioElement.src = url
      audioElement.addEventListener('loadedmetadata', () => {
        this.setDuration(audioElement)
      })
      // 判断文件资源类型
      let filetype = file.name.split('.')[file.name.split('.').length - 1].toLowerCase()
      if (filetype === 'mp4') {
        filetype = 'video'
      } else if (filetype === 'pdf') {
        filetype = 'pdf'
      }
      this.resource.genre = filetype
    },
    uploadSucceeded (response, file) {
      this.showProgress = false
      this.videoUploadPercent = 0
      this.resource.course = this.courseId
      let funcName = 'createCourseResourceInfo'
      let data = Object.assign({}, this.resource)
      api[funcName](data).then(res => {
        this.resourceList.push(res.data.data)
        this.$message({
          message: '资源上传成功！',
          duration: 1000,
          type: 'success'
        })
      }).catch((e) => {
      })
    },
    format () {
      let percentage = this.videoUploadPercent
      return percentage === 100 ? '完成' : `${percentage}%`
    },
    videoUploadProcess (event, file, fileList) {
      this.showProgress = true
      this.videoUploadPercent = file.percentage.toFixed(0) * 1
    }
  },
  watch: {
    '$route' (newVal, oldVal) {
      this.courseId = newVal.params.courseId
      this.routeName = newVal.name
      this.getResourceList(this.currentPage)
    },
    'keyword' () {
      this.currentChange()
    }
  }
}
</script>
